/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/*
 * Ventas.java
 *
 * Created on Jul 27, 2011, 6:31:34 PM
 */

package dced.ui;
import dced.entity.Item;
import dced.entity.Venta;
import dced.entity.Inventario;
import dced.util.HibernateUtil;
import java.math.BigDecimal;
import java.util.*;
import javax.swing.table.DefaultTableModel;
import org.hibernate.*;
import javax.swing.*;
import java.util.Date;
import java.util.Calendar;
import java.text.SimpleDateFormat;
import java.text.DateFormat;
/**
 *
 * @author antonio
 */
public class V_Ventas extends javax.swing.JFrame {

    /** Creates new form Ventas */
    public V_Ventas() {
       initComponents();
                Inventario inv=new Inventario();

               runQueryAll(QUERY_inv);

    }
    
    
    double precioTotal=0;
    double subtotal=0;
    double iva = 0;
    public static Vector tablaVenta = new Vector();
    private static Vector<Double> precios = new Vector<Double>();
    private static Vector<Short> existencia = new Vector<Short>();
  

    
  // ***** LLena el combobox con todo el contenido de inventario
    private void displayResult(List resultList) {
        
 //   jComboBox1.
    Vector tableData = new Vector();
   

    for(Object o : resultList) {
        Inventario inventario = (Inventario)o;
        //Vector<Object> oneRow = new Vector<Object>();
        jComboBox1.addItem(inventario.getDescripcionInventario());
        precios.add(inventario.getPrecioUnitarioInventario());
        existencia.add(inventario.getCantidadInventario());
        //tableData.add(oneRow);
    }
    
    
//    jComboBox1.setModel(new ComboBoxModel());
            
            //.setModel(new DefaultTableModel(tableData, tableHeaders));
}
    
    private static String QUERY_inv="from Inventario";
//    private static String QUERY_desc="descripcion_inventario from Inventario";
    

        
    private void runQueryAll(String hql) {
       try {
        Session session = HibernateUtil.getSessionFactory().openSession();
        session.beginTransaction();
        Query q = session.createQuery(hql);
        List resultList = q.list();
        displayResult(resultList);
        session.getTransaction().commit();
    } catch (HibernateException he) {
        he.printStackTrace();
        
    }
    }
    
    
    
    // query con el que se llena el resultList que se va a meter al combobox
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        jPanel1 = new javax.swing.JPanel();
        jComboBox1 = new javax.swing.JComboBox();
        jButton1 = new javax.swing.JButton();
        jScrollPane1 = new javax.swing.JScrollPane();
        jTable1 = new javax.swing.JTable();
        cantidad = new javax.swing.JTextField();
        jLabel1 = new javax.swing.JLabel();
        jButton2 = new javax.swing.JButton();
        textTotal = new javax.swing.JTextField();
        jLabel2 = new javax.swing.JLabel();
        cancelarActionPerformed = new javax.swing.JButton();
        textIVA = new javax.swing.JTextField();
        textSub = new javax.swing.JTextField();
        jLabel3 = new javax.swing.JLabel();
        jLabel4 = new javax.swing.JLabel();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);

        jComboBox1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                jComboBox1ActionPerformed(evt);
            }
        });

        jButton1.setText("Agregar");
        jButton1.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                AgregarActionPerformed(evt);
            }
        });

        jTable1.setModel(new javax.swing.table.DefaultTableModel(
            new Object [][] {

            },
            new String [] {
                "Cantidad", "Descripcion", "Precio Unitario"
            }
        ));
        jScrollPane1.setViewportView(jTable1);

        jLabel1.setText("Cantidad");

        jButton2.setText("Registrar Venta");
        jButton2.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                registrarventaActionPerformed(evt);
            }
        });

        jLabel2.setText("Total");

        cancelarActionPerformed.setText("Cancelar");
        cancelarActionPerformed.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                cancelarActionPerformedActionPerformed(evt);
            }
        });

        jLabel3.setText("I.V.A.");

        jLabel4.setText("SubTotal");

        javax.swing.GroupLayout jPanel1Layout = new javax.swing.GroupLayout(jPanel1);
        jPanel1.setLayout(jPanel1Layout);
        jPanel1Layout.setHorizontalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(66, 66, 66)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                            .addComponent(cancelarActionPerformed)
                            .addComponent(jButton2)))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(128, 128, 128)
                        .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)))
                .addGap(160, 160, 160)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                            .addComponent(jLabel3)
                            .addComponent(jLabel4)
                            .addComponent(jLabel2))
                        .addComponent(jLabel1))
                    .addComponent(cantidad, javax.swing.GroupLayout.PREFERRED_SIZE, 46, javax.swing.GroupLayout.PREFERRED_SIZE))
                .addGap(18, 18, 18)
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addComponent(jButton1)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(51, 51, 51)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING, false)
                            .addComponent(textSub, javax.swing.GroupLayout.DEFAULT_SIZE, 92, Short.MAX_VALUE)
                            .addComponent(textIVA)
                            .addComponent(textTotal))))
                .addGap(183, 183, 183))
            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel1Layout.createSequentialGroup()
                    .addGap(61, 61, 61)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 579, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(121, Short.MAX_VALUE)))
        );
        jPanel1Layout.setVerticalGroup(
            jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(jPanel1Layout.createSequentialGroup()
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addGap(27, 27, 27)
                        .addComponent(jLabel1)
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(jButton1)
                            .addComponent(jComboBox1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(cantidad, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 431, Short.MAX_VALUE)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(textSub, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel4))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED)
                        .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                            .addComponent(textIVA, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                            .addComponent(jLabel3))
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED))
                    .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, jPanel1Layout.createSequentialGroup()
                        .addContainerGap()
                        .addComponent(jButton2)
                        .addGap(29, 29, 29)))
                .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                    .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.TRAILING)
                        .addComponent(textTotal, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                        .addComponent(cancelarActionPerformed))
                    .addGroup(jPanel1Layout.createSequentialGroup()
                        .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.UNRELATED)
                        .addComponent(jLabel2)))
                .addGap(32, 32, 32))
            .addGroup(jPanel1Layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                .addGroup(jPanel1Layout.createSequentialGroup()
                    .addGap(114, 114, 114)
                    .addComponent(jScrollPane1, javax.swing.GroupLayout.PREFERRED_SIZE, 372, javax.swing.GroupLayout.PREFERRED_SIZE)
                    .addContainerGap(136, Short.MAX_VALUE)))
        );

        javax.swing.GroupLayout layout = new javax.swing.GroupLayout(getContentPane());
        getContentPane().setLayout(layout);
        layout.setHorizontalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, 761, Short.MAX_VALUE)
                .addContainerGap())
        );
        layout.setVerticalGroup(
            layout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
            .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, layout.createSequentialGroup()
                .addContainerGap()
                .addComponent(jPanel1, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        pack();
    }// </editor-fold>//GEN-END:initComponents

    
    
    private void jComboBox1ActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_jComboBox1ActionPerformed
        // TODO add your handling code here:
   //     System.out.print(jComboBox1.getSelectedItem());
    }//GEN-LAST:event_jComboBox1ActionPerformed

    
    // agrega a tablaVenta el artículo seleccionado del combobox y lo mada a desplegarse en la ventana
    private void AgregarActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_AgregarActionPerformed
        // TODO add your handling code here:
        
     //   jComboBox1.getSelectedItem();

        Vector<String> tableHeaders = new Vector<String>();
  //  Vector tablaVenta = new Vector();
        tableHeaders.add("Cantidad"); 
        tableHeaders.add("Descripción");
        tableHeaders.add("Precio Unitario");

if((existencia.get(jComboBox1.getSelectedIndex())-Short.parseShort(cantidad.getText()))>=0){

        Vector<Object> oneRow = new Vector<Object>();
        oneRow.add(Short.parseShort(cantidad.getText()));
        oneRow.add(jComboBox1.getSelectedItem());
        oneRow.add(precios.get(jComboBox1.getSelectedIndex()));
        //precioTotal+=(double)(precios.get(jComboBox1.getSelectedIndex()))*(Double.parseDouble(cantidad.getText()));
  
        
    
      subtotal+=(double)(precios.get(jComboBox1.getSelectedIndex()))*(Double.parseDouble(cantidad.getText()));
      iva=subtotal * .16;
      precioTotal=subtotal + iva;
      tablaVenta.add(oneRow);
      jTable1.setModel(new DefaultTableModel(tablaVenta, tableHeaders));
      
      System.out.println(precioTotal);
      textTotal.setText(String.valueOf(precioTotal));
      textIVA.setText(String.valueOf(iva));
      textSub.setText(String.valueOf(subtotal));
      

}
else{
    JOptionPane pane = new JOptionPane();
    JOptionPane.showMessageDialog(null,"Máximo " + existencia.get(jComboBox1.getSelectedIndex()));
}
    }//GEN-LAST:event_AgregarActionPerformed

    
    // esta la uso solo para probar el botón registrar venta
    //despliega en terminal lo que hay en tablaVenta AQUÍ DEBE IR EL CÓDIGO PARA AGREGAR LA VENTA E ITEM A LA BD
    private void registrarventaActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_registrarventaActionPerformed
        // TODO add your handling code here:
   //     Item item = new Item();
  
        System.out.print(tablaVenta);
        
       
        //ACTUALIZA INVENTARIO, RESTANDO LO QUE SE HA VENDIDO
    Inventario inv = new Inventario();
    Session session = HibernateUtil.getSessionFactory().openSession();
    session.beginTransaction();
    
    for(Object o : tablaVenta) {
        Vector fila = (Vector)o;
        Query query = session.createQuery("update Inventario set Cantidad_Inventario = Cantidad_Inventario - :newcantidad  where Descripcion_Inventario = :descripcion");
        query.setParameter("newcantidad", fila.elementAt(0)); // existencia.get(jComboBox1.getSelectedIndex())-Short.parseShort(cantidad.getText())
        query.setParameter("descripcion", fila.elementAt(1)); // jComboBox1.getSelectedItem()
        int result = query.executeUpdate();
        }
    session.getTransaction().commit();
    
    //AGREGA VENTA A LA VENTA ACTUAL A LA TABLA VENTA
    Date fecha = new Date();
    fecha.toString();
    
    Venta venta =new Venta();
    venta.setCreditoVenta(null);
    venta.setDescripcionVenta(null);
    venta.setFechaVenta(fecha);
    venta.setIdVenta(null);
    venta.setPrecioTotalVenta(BigDecimal.valueOf(precioTotal));
    
    Session agregaventa = HibernateUtil.getSessionFactory().openSession();
    Transaction tx = session.beginTransaction();
   
    agregaventa.save(venta);
    agregaventa.flush();
    agregaventa.clear();
        
    tx.commit();
    agregaventa.close();
    
    
    
    
    
   
    tablaVenta.clear();
    //cerrar = new java.awt.AWTEvent(null) {}
    V_Ventas.this.dispose();
    
    }//GEN-LAST:event_registrarventaActionPerformed

    private void cancelarActionPerformedActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_cancelarActionPerformedActionPerformed
        // TODO add your handling code here:
        tablaVenta.clear();
        V_Ventas.this.dispose();
    }//GEN-LAST:event_cancelarActionPerformedActionPerformed

    /**
    * @param args the command line arguments
    */
    public static void main(String args[]) {
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                new V_Ventas().setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JButton cancelarActionPerformed;
    private javax.swing.JTextField cantidad;
    private javax.swing.JButton jButton1;
    private javax.swing.JButton jButton2;
    private javax.swing.JComboBox jComboBox1;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel jLabel2;
    private javax.swing.JLabel jLabel3;
    private javax.swing.JLabel jLabel4;
    private javax.swing.JPanel jPanel1;
    private javax.swing.JScrollPane jScrollPane1;
    private javax.swing.JTable jTable1;
    private javax.swing.JTextField textIVA;
    private javax.swing.JTextField textSub;
    private javax.swing.JTextField textTotal;
    // End of variables declaration//GEN-END:variables

}
